package cn.wolfcode.luowowo.website.web.util;


import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    public static void addCookie(HttpServletResponse response,String name,int time,String value){

        //创建cookie对象,通过resp对象将cookie返回给浏览器
        Cookie cookie = new Cookie("token", value);
        cookie.setPath("/");
        //设置cookie过期时间为30分钟
        cookie.setMaxAge(time);
        response.addCookie(cookie);
    }

    public static String getToken(HttpServletRequest request,HttpServletResponse response){
        //获取所有的cookie
        Cookie[] cookies = request.getCookies();
        String token = null;
        if (cookies != null && cookies.length >0){
            //遍历
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")){
                    token = cookie.getValue();
                    //延长token时间
                    CookieUtil.addCookie(response,"token", RedisKeys.USER_LOGIN_TOKEN.getTime().intValue(),token);
                    break;
                }
            }
        }
        return token;
    }


}
